﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Security;

using GroundWater.Data;
using GroundWater.BusinessActions;

using UserTable = GroundWater.Data.UserDataSet.UsersDataTable;
using UserRow = GroundWater.Data.UserDataSet.UsersRow;


namespace GroundWater.AllowAccess
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class LoginHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            if (this.ValidateUser(username, password))
            {
                context.Response.Write("1");
                //FormsAuthentication.RedirectFromLoginPage(username, false);//_persistCookie.Checked
                FormsAuthentication.SetAuthCookie(username, false);
            }
            else
            {
                context.Response.Write("0");
            }
            return;
        }

        private bool ValidateUser(string username, string password) //Authenticate(
        {
            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                return false;
            }

            UserRow row = Users.GetById(username, false);

            if (row != null && row.Password == password)
            {
                SiteUtil.SetString("Username", username);
                return true;
            }

            return false;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
